package io.potato.ts.repository;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import io.potato.ts.domain.SmsSendingRecord;

/**
 * 等待发送的短信(sms_sending_record)数据访问接口
 * 
 * @author timl
 *
 * <p>2019-01-07 15:13:58</p>
 */
public interface SmsSendingRecordRepository extends JpaRepository<SmsSendingRecord, Long> {
	
	/**
	 * 查找待发送的记录
	 * @param sendTime  待发送时间
	 * @return
	 */
	@Query(nativeQuery = true, 
			value = "select * from :table where "
					+ "send_time <= :sendTime AND status = 0 "
					+ "AND try_times = 0 limit 20000")
	List<SmsSendingRecord> findToSend(
			@Param("sendTime") LocalDateTime sendTime, 
			@Param("table") String table);
	
	/**
	 * 查询发送失败的记录
	 * @param sendTime 
	 * @param tryTimes
	 * @param tryAt
	 * @return
	 */
	@Query(nativeQuery = true, 
			value = "select * from :table where "
					+ "send_time <= :sendTime AND status = 0 "
					+ "AND try_times = :tryTimes AND try_at <= :tryAt limit 10000")
	List<SmsSendingRecord> findFailedToSend(
			@Param("sendTime") LocalDateTime sendTime, 
			@Param("tryTimes") Integer tryTimes, 
			@Param("tryAt") LocalDateTime tryAt,
			@Param("table") String table);
	
}
